<?php

namespace App\Observers;

use App\Models\Device;
use Illuminate\Support\Carbon;

class DeviceObserver
{
    /**
     * Handle the device "created" event.
     *
     * @param \App\Models\Device $device
     * @return void
     */
    public function created(Device $device)
    {
        //
    }

    /**
     * Handle the device "updated" event.
     *
     * @param \App\Models\Device $device
     * @return void
     */
    public function updated(Device $device)
    {
        //
    }

    /**
     * Handle the device "deleted" event.
     *
     * @param \App\Models\Device $device
     * @return void
     */
    public function deleted(Device $device)
    {
        //
    }

    /**
     * Handle the device "restored" event.
     *
     * @param \App\Models\Device $device
     * @return void
     */
    public function restored(Device $device)
    {
        //
    }

    /**
     * Handle the device "force deleted" event.
     *
     * @param \App\Models\Device $device
     * @return void
     */
    public function forceDeleted(Device $device)
    {
        //
    }

    public function creating(Device $model)
    {
//        $model->created_at = Carbon::now();
        $model->code = uniqid();
    }

    public function saving(Device $model)
    {
        if($model->manager){
            $model->manager_name = $model->manager->name;
            $model->manager_phone_number = $model->manager->phone;
        }
        if($model->phone_number_1){
            $model->number_1=$model->phone_number_1->number;
            $model->imei_1=$model->phone_number_1->imei;
        }else{
            $model->number_1=$model->imei_1=null;
        }
        if($model->phone_number_2){
            $model->number_2=$model->phone_number_2->number;
            $model->imei_2=$model->phone_number_2->imei;
        }else{
            $model->number_2=$model->imei_2=null;
        }
    }
    public function saved(Device $model){
        if($model->manager){
            $model->manager->count_device=Device::query()->where('manager_id',$model->manager->id)->count();
            $model->manager->save();
        }
    }
}
